package com.jh3502.vivo.function.reimnew;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.TextView;

import com.jh3502.vivo.R;
import com.jh3502.vivo.base.BaseActivity;
import com.jh3502.vivo.function.dialog.BankChooseDialog;
import com.jh3502.vivo.function.dialog.PlaceChooseDialog;
import com.jh3502.vivo.function.dialog.ReimTypeChooseDialog;
import com.jh3502.vivo.function.dialog.TravelNumChooseBean;
import com.jh3502.vivo.function.dialog.TravelNumChooseDialog;
import com.jh3502.vivo.function.dialog.TravelPersonChooseBean;
import com.jh3502.vivo.function.dialog.TravelPersonChooseDialog;
import com.jh3502.vivo.function.reimnew.beans.CategoryInfoBean;
import com.jh3502.vivo.function.reimnew.beans.ClfBean;
import com.jh3502.vivo.function.reimnew.beans.CzcfBean;
import com.jh3502.vivo.function.reimnew.beans.DetailBean;
import com.jh3502.vivo.function.reimnew.beans.ReimNewBean;
import com.jh3502.vivo.function.reimnew.beans.SubBean;
import com.jh3502.vivo.function.reimnew.beans.ZsfBean;
import com.jh3502.vivo.utils.Utils;
import com.jh3502.vivo.view.MyRecyclerView;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

import static com.jh3502.vivo.function.reimnew.ReimNewItemAdapter.CLF;
import static com.jh3502.vivo.function.reimnew.ReimNewItemAdapter.CZCF;
import static com.jh3502.vivo.function.reimnew.ReimNewItemAdapter.SUB;
import static com.jh3502.vivo.function.reimnew.ReimNewItemAdapter.ZSF;


/**
 * @author harisucici
 * @version 2018/12/10 17:40
 * name
 * todo
 * @email harisucici@gmail.com
 */
public class ReimNewActivity extends
        BaseActivity<ReimNewPresenter.ReimNewView, ReimNewPresenter>
        implements ReimNewPresenter.ReimNewView, ReimNewItemInterface {
    public static final int FROM_PERSON_CHOOSE = 0;
    public static final int FROM_NUM_CHOOSE = 1;
    public static final int FROM_PLACE_CHOOSE = 2;
    public static final int FROM_REIM_TYPE_CHOOSE = 3;
    public static final int FROM_ITEM_OUT_CHOOSE = 4;
    public static final int FROM_ITEM_CAR_CHOOSE = 5;
    public static final int FROM_ITEM_OUT_MONEY_CHOOSE = 6;
    public static final int FROM_ITEM_PHOTO_CHOOSE = 7;
    public static final int FROM_BANK_CHOOSE = 8;

    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.reim_new_num)
    TextView reimNewNum;
    @BindView(R.id.reim_new_person)
    TextView reimNewPerson;
    @BindView(R.id.reim_new_travel_num)
    TextView reimNewTravelNum;
    @BindView(R.id.reim_new_recycler)
    MyRecyclerView reimNewRecycler;
    @BindView(R.id.reim_new_dep_name)
    TextView reimNewDepName;
    @BindView(R.id.reim_new_dep_num)
    EditText reimNewDepNum;
    @BindView(R.id.reim_new_dep_bank)
    TextView reimNewDepBank;
    @BindView(R.id.new_total_1)
    TextView newTotal1;
    @BindView(R.id.new_total_2)
    TextView newTotal2;
    @BindView(R.id.new_all)
    TextView newAll;
    private ReimNewAdapter mAdapter;
    private ReimNewBean reimNewBean;
    private List<DetailBean> detailBeans;
    private int typeItem;
    private int positionMain;
    private int positionItem;
    private int chosen;
    private int level;
    private DetailBean tempDetailBean;

    @Override
    public ReimNewPresenter initPresenter() {
        return new ReimNewPresenter();
    }

    @Override
    protected int setViewId() {
        return R.layout.activity_reim_new;
    }

    @Override
    protected void initView() {
        toolbar.setTitle("");
        toolbarTitle.setText("报销申请");
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        reimNewRecycler.setNestedScrollingEnabled(false);
        mPresenter.setReimNewView(this);


    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_note, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                break;
            case R.id.action_note:
                showShortToast("不知道干嘛用");
                break;
            default:
        }
        return true;
    }

    @Override
    protected void initData() {
        reimNewBean = new ReimNewBean();
        detailBeans = reimNewBean.getDetail();
    }

    @Override
    protected void doOnDestroy() {

    }

    @Override
    protected void doOnResume() {

    }

    @Override
    protected void doOnSaveInstanceState(Bundle savedInstanceState) {

    }

    @Override
    public void responseError(int code, String msg) {
        showShortToast(msg);

    }

    @OnClick(R.id.reim_new_person)
    public void onReimNewPersonClicked() {
        Intent intent = new Intent(getActContext(), TravelPersonChooseDialog.class);
        startActivityForResult(intent, FROM_PERSON_CHOOSE);
    }

    @OnClick(R.id.reim_new_travel_num)
    public void onReimNewTravelNumClicked() {
        if (TextUtils.isEmpty(reimNewPerson.getText().toString().trim())) {
            showShortToast("请选择报销人员");
            return;
        }
        Intent intent = new Intent(getActContext(), TravelNumChooseDialog.class);
        intent.putExtra("name", reimNewPerson.getText().toString().trim());
        startActivityForResult(intent, FROM_NUM_CHOOSE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case FROM_PERSON_CHOOSE:
                    reimNewPerson.setText(data.getStringExtra("personName"));
                    reimNewBean.setPersonId(data.getIntExtra("personId", -1));
                    reimNewBean.setPersonName(data.getStringExtra("personName"));
                    reimNewBean.setDeptId(data.getIntExtra("deptId", -1));
                    level = data.getIntExtra("level", -1);
                    reimNewBean.setLevel(level);
                    reimNewBean.setPostId(data.getIntExtra("postId", -1));
                    reimNewBean.setMoneyCzcf(data.getDoubleExtra("standard", -1));
                    Map<String, Object> body = new HashMap<>(2);
                    body.put("userId", data.getIntExtra("personId", -1));
                    mPresenter.toFindaccount(body);
                    break;
                case FROM_NUM_CHOOSE:
                    reimNewTravelNum.setText(data.getStringExtra("travelNo"));
                    reimNewBean.setTravelNo(data.getStringExtra("travelNo"));
                    reimNewBean.setTravelId(data.getIntExtra("travelId", -1));
                    Date date1 = Utils.getInstance().string2Date(data.getStringExtra("startDate"));
                    Date date2 = Utils.getInstance().string2Date(data.getStringExtra("endDate"));
                    int days = Utils.getInstance().getDateCount(date1, date2);
                    for (int i = 0; i < days; i++) {
                        DetailBean detailBean = new DetailBean();
                        detailBean.setDate(Utils.getInstance().getOtherDay(date1, i));
                        CategoryInfoBean bean = new CategoryInfoBean();
                        detailBean.setCategoryInfo(bean);
                        detailBeans.add(detailBean);
                    }
                    mAdapter = new ReimNewAdapter(this, detailBeans);
                    mAdapter.setReimNewItemInterface(this);
                    mAdapter.setTaxi(reimNewBean.getMoneyCzcf());
                    // 刷新动画
                    ((DefaultItemAnimator) reimNewRecycler.getItemAnimator()).setSupportsChangeAnimations(false);
                    reimNewRecycler.setAdapter(mAdapter);
                    mAdapter.setChoosePlace(position -> {
                        Intent intent = new Intent(getActContext(), PlaceChooseDialog.class);
                        intent.putExtra("place", data.getExtras().getString("place"));
                        intent.putExtra("position", position);
                        startActivityForResult(intent, FROM_PLACE_CHOOSE);
                    });
                    mAdapter.setAddReim(position -> {
                        if (TextUtils.isEmpty(reimNewBean.getDetail().get(position).getCityname())) {
                            showShortToast("请选择城市");
                            return;
                        }
                        Intent intent = new Intent(getActContext(), ReimTypeChooseDialog.class);
                        intent.putExtra("position", position);
                        startActivityForResult(intent, FROM_REIM_TYPE_CHOOSE);

                    });
                    break;
                case FROM_PLACE_CHOOSE:
                    int pos = data.getIntExtra("position", -1);
                    tempDetailBean = detailBeans.get(pos);
                    tempDetailBean.setCityname(data.getStringExtra("cityname"));
                    tempDetailBean.setAdcode(data.getStringExtra("adcode"));
                    tempDetailBean.setCategoryInfo(new CategoryInfoBean());
                    mAdapter.notifyDataSetChanged();
                    Map<String, Object> bodyHotel = new HashMap<>(2);
                    bodyHotel.put("adcode", data.getStringExtra("adcode"));
                    bodyHotel.put("level", level);
                    mPresenter.toFindHotelStandard(bodyHotel);
                    break;
                case FROM_REIM_TYPE_CHOOSE:
                    // 0 差旅，1 住宿 2 出租 3 补助
                    int type = data.getIntExtra("type", -1);
                    if (type == 0) {
                        ClfBean clfBean = new ClfBean();
                        clfBean.setTitle(data.getStringExtra("title"));
                        detailBeans.get(data.getIntExtra("position", 0)).
                                getCategoryInfo().getClf().add(clfBean);
                    } else if (type == 1) {
                        ZsfBean zsfBean = new ZsfBean();
                        zsfBean.setTitle(data.getStringExtra("title"));
                        detailBeans.get(data.getIntExtra("position", 0)).
                                getCategoryInfo().getZsf().add(zsfBean);
                    } else if (type == 2) {
                        CzcfBean czcfBean = new CzcfBean();
                        czcfBean.setTitle(data.getStringExtra("title"));
                        detailBeans.get(data.getIntExtra("position", 0)).
                                getCategoryInfo().getCzcf().add(czcfBean);
                    } else if (type == 3) {
                        SubBean subsidyBean = new SubBean();
                        subsidyBean.setTitle(data.getStringExtra("title"));
                        detailBeans.get(data.getIntExtra("position", 0)).
                                getCategoryInfo().getSub().add(subsidyBean);
                    }
                    mAdapter.notifyDataSetChanged();
                    break;
                case FROM_ITEM_OUT_CHOOSE:
                    typeItem = data.getIntExtra("typeItem", -1);
                    chosen = data.getIntExtra("chosen", -1);
                    positionMain = data.getIntExtra("positionMain", -1);
                    positionItem = data.getIntExtra("positionItem", -1);
                    if (typeItem == CLF) {
                        detailBeans.get(positionMain).getCategoryInfo().getClf().get(positionItem).setOverTop(chosen);
                    } else if (typeItem == ZSF) {
                        detailBeans.get(positionMain).getCategoryInfo().getZsf().get(positionItem).setOverTop(chosen);
                    }
                    if (chosen == 1) {
                        reimNewBean.setOverTop(1);
                    }
                    mAdapter.notifyDataSetChanged();
                    break;
                case FROM_ITEM_OUT_MONEY_CHOOSE:
                    typeItem = data.getIntExtra("typeItem", -1);
                    chosen = data.getIntExtra("chosen", -1);
                    positionMain = data.getIntExtra("positionMain", -1);
                    positionItem = data.getIntExtra("positionItem", -1);
                    if (typeItem == CLF) {
                    } else if (typeItem == ZSF) {
                        detailBeans.get(positionMain).getCategoryInfo().getZsf().get(positionItem).setStandard(chosen + 1);
                    }
                    if (chosen == 1) {
                        reimNewBean.setOverTop(1);
                    }
                    mAdapter.notifyDataSetChanged();
                    break;

                case FROM_ITEM_CAR_CHOOSE:
                    typeItem = data.getIntExtra("typeItem", -1);
                    String carname = data.getStringExtra("name");
                    String cartype = data.getStringExtra("type");
                    positionMain = data.getIntExtra("positionMain", -1);
                    positionItem = data.getIntExtra("positionItem", -1);
                    if (typeItem == CLF) {
                        detailBeans.get(positionMain).getCategoryInfo().getClf().get(positionItem).setTraffic(carname);
                        detailBeans.get(positionMain).getCategoryInfo().getClf().get(positionItem).setType(cartype);
                    }
                    mAdapter.notifyDataSetChanged();
                    break;
                case FROM_ITEM_PHOTO_CHOOSE:
                    typeItem = data.getIntExtra("typeItem", -1);
                    positionMain = data.getIntExtra("positionMain", -1);
                    positionItem = data.getIntExtra("positionItem", -1);
                    if (typeItem == CLF) {
                        ClfBean clfBean = detailBeans.get(positionMain).getCategoryInfo().getClf().get(positionItem);
                        List<String> files = clfBean.getFiles();
                        files.add(data.getStringExtra("path"));
                    } else if (typeItem == ZSF) {
                        ZsfBean ZsfBean = detailBeans.get(positionMain).getCategoryInfo().getZsf().get(positionItem);
                        List<String> files = ZsfBean.getFiles();
                        files.add(data.getStringExtra("path"));
                    } else if (typeItem == CZCF) {
                        CzcfBean CzcfBean = detailBeans.get(positionMain).getCategoryInfo().getCzcf().get(positionItem);
                        List<String> files = CzcfBean.getFiles();
                        files.add(data.getStringExtra("path"));
                    } else if (typeItem == SUB) {
                        SubBean SubBean = detailBeans.get(positionMain).getCategoryInfo().getSub().get(positionItem);
                        List<String> files = SubBean.getFiles();
                        files.add(data.getStringExtra("path"));
                    }
                    mAdapter.notifyDataSetChanged();
                    break;
                case FROM_BANK_CHOOSE:
                    reimNewDepBank.setText(data.getStringExtra("bankName"));
                    break;
                default:
            }
        }
    }

    @Override
    public void findExpensePersonSuccess(List<TravelPersonChooseBean> travelPersonChooseBeans) {

    }

    @Override
    public void findTravelFormSuccess(List<TravelNumChooseBean> travelNumChooseBeans) {

    }

    @Override
    public void findaccountSuccess(Map<String, Object> map) {
        reimNewBean.setOpenbank((String) map.get("openBank"));
        reimNewBean.setAccountNum((String) map.get("accountNum"));
        reimNewDepName.setText((String) map.get("accountName"));
        reimNewDepNum.setText((String) map.get("accountNum"));
        reimNewDepBank.setText((String) map.get("openBank"));
    }

    @Override
    public void submitExpenseSuccess() {
        showShortToast("提交成功");
        onBackPressed();
    }


    @Override
    public void findHotelStandard(double v) {
        // 该地点住宿费额度
        tempDetailBean.setMoneyZsf(v);

    }


    @OnClick(R.id.reim_new_dep_bank)
    public void onReimNewDepBankClicked() {
        Intent intent = new Intent(getActContext(), BankChooseDialog.class);
        startActivityForResult(intent, FROM_BANK_CHOOSE);
    }

    @OnClick(R.id.cancel)
    public void onCancelClicked() {
        onBackPressed();
    }

    @OnClick(R.id.submit)
    public void onSubmitClicked() {
        Map<String, Object> body = new HashMap<>(2);
        body.put("personId", reimNewBean.getPersonId());
        body.put("personName", reimNewBean.getPersonName());
        body.put("deptId", reimNewBean.getDeptId());
        body.put("level", reimNewBean.getLevel());
        body.put("postId", reimNewBean.getPostId());
        body.put("travelNo", reimNewBean.getTravelNo());
        body.put("travelId", reimNewBean.getTravelId());
        body.put("accountNum", reimNewBean.getAccountNum());
        body.put("openbank", reimNewBean.getOpenbank());
        body.put("overTop", reimNewBean.getOverTop());
        body.put("actualMoney", reimNewBean.getActualMoney());
        body.put("detail", reimNewBean.getDetail());
        mPresenter.toSubmitExpense(body);
    }

    @Override
    public void refreshAdapter(int positionMain, BigDecimal bigDecimal, double v) {
        BigDecimal amountAll = new BigDecimal(0);
        double outAll = 0;
        reimNewBean.getDetail().get(positionMain).setApplyMoney(bigDecimal.doubleValue());
        reimNewBean.getDetail().get(positionMain).setOutMoney(v);
        reimNewBean.getDetail().get(positionMain).setActualMoney(Utils.getInstance().sub(bigDecimal.doubleValue(), v));

        refreshRecycler(positionMain);
        for (DetailBean detailBean : detailBeans) {
            amountAll = Utils.getInstance().add(amountAll, detailBean.getApplyMoney());
            outAll = Utils.getInstance().add(outAll, detailBean.getOutMoney());
        }
        newTotal1.setText(amountAll.doubleValue() + "");
        newTotal2.setText(outAll + "");
        newAll.setText(Utils.getInstance().sub(amountAll.doubleValue(), outAll) + "");
    }

    private void refreshRecycler(int position) {
        Handler handler = new Handler();
        Runnable r = () -> mAdapter.notifyItemChanged(position);
        handler.post(r);
    }
}
